<?php

namespace app\admin\controller\letter\user\daisong;

use app\admin\model\prison\DetentionPrison;
use app\admin\model\shopro\Config;
use app\admin\model\shopro\data\Area;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 代送业务
 *
 * @icon fa fa-circle-o
 */
class Log extends Backend
{

    /**
     * Log模型对象
     * @var \app\admin\model\letter\user\daisong\Log
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\letter\user\daisong\Log;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            if ($row['status'] == 0 && $params['status'] == 1) {
                if ($params['price'] <= 0) {
                    $this->error('金额不能小于0');
                }
                $user_id = $row['user_id'];
                //生成辅单
                $images = explode(',', $params['images']);
                $orderItem = $this->mergeItemOrder($user_id, 100, $params['remark'], $images[0], $params['price']);
                //生成总单
                $orderData = $this->addOrder($user_id, $ids, $params['price']);
                //生产地址单
                $orderDataAddress = $this->addRessOrder1($row['jy_id'], $user_id, $params);
                $order_id = Db::table('jy_shopro_order')->insertGetId($orderData);
                $orderItem['order_id'] = $order_id;
                if ($orderDataAddress) {
                    $orderDataAddress['order_id'] = $order_id;
                    Db::table('jy_shopro_order_address')->insert($orderDataAddress);
                }
                $order_item_id = Db::table('jy_shopro_order_item')->insert($orderItem);
                $params['order_id'] = $order_id;
                if ($order_id && $order_item_id) {
                    // 发送短信
                    sendSms($params['phone'], $orderData['order_sn']);
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                }
            } else {
                if ($params['status'] == 0) {
                    unset($params['status']);
                }
                $result = $row->allowField(true)->save($params);
                Db::commit();
            }

        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function mergeItemOrder($user_id, $model_id, $goods_title, $image, $pay_price)
    {
        $orderItem = json_decode('{"user_id":0,"order_id":"","goods_id":"40","goods_type":"virtual","goods_sku_price_id":"47","activity_id":0,"activity_type":null,"item_goods_sku_price_id":0,"goods_sku_text":null,"goods_title":"\u4e49\u8bca","goods_image":"https:\/\/admin.taobaotnxh.com\/uploads\/20231119\/8266c9e5304fba17807ca1a2b3ea2781.png","goods_original_price":"0.00","discount_fee":"0.00","goods_price":"0.00","goods_num":1,"goods_weight":0,"dispatch_status":0,"dispatch_fee":0,"dispatch_type":"selfetch","dispatch_id":2,"aftersale_status":0,"comment_status":0,"refund_status":0,"ext":"{\"dispatch_date\":\"\",\"dispatch_phone\":\"\"}"}', true);
        $orderItem['user_id'] = $user_id;
        $goods_sku_price = Db::table('jy_shopro_goods_sku_price')->where('id', $model_id)->find();
        $orderItem['goods_id'] = $goods_sku_price['goods_id'];
        $orderItem['goods_sku_text'] = $goods_sku_price['goods_sku_text'];
        $orderItem['goods_title'] = $goods_title;
        $orderItem['goods_price'] = $pay_price;
        $orderItem['pay_fee'] = $pay_price;
        $orderItem['goods_original_price'] = $pay_price;
        $orderItem['goods_num'] = 1;
        $orderItem['goods_type'] = 'virtual';
        $orderItem['item_goods_sku_price_id'] = $goods_sku_price['id'];
        $orderItem['goods_image'] = cdnurl($image, true);
        return $orderItem;
    }


    public function addOrder($user_id, $daisong_id, $pay_price = 0)
    {
        $order = json_decode('{"order_sn":"","user_id":0,"type":"goods","activity_type":"","goods_amount":"0.00","dispatch_amount":"0.00","score_amount":0,"invoice_status":-1,"status":0,"remark":"","platform":"H5","ext":"[]"}', true);
        $order['user_id'] = $user_id;
        $order['pay_fee'] = $pay_price;
        $order['status'] = 'unpaid';
        $order['original_pay_fee'] = $pay_price;
        $order['goods_amount'] = $pay_price;
        $order['order_amount'] = $pay_price;
        $order['remain_pay_fee'] = $pay_price;
        $order['daisong_id'] = $daisong_id;
        $order['createtime'] = time();
        $order['updatetime'] = time();
        $order['platform'] = 'WechatMiniProgram';
        $close_time = Config::getConfigs('shop.order.auto_close');
        $close_time = $close_time && $close_time > 0 ? $close_time : 0;
        $order['ext'] = json_encode([
            'expired_time' => time() + ($close_time * 60)
        ]);
        $order['type'] = 'pt_goods';
        $order['order_sn'] = 'ph' . date('Ymd') . $user_id . time() . mt_rand(10, 100);
        return $order;
    }

    public function addRessOrder($user_id, $order_id)
    {
        $user_address = Db::table('jy_shopro_user_address')->where(['is_default' => 1, 'user_id' => $user_id])->find();
        if ($user_address) {
            $order['mobile'] = $user_address['mobile'];
            $order['consignee'] = $user_address['consignee'];
            $order['province_name'] = $user_address['province_name'];
            $order['city_name'] = $user_address['city_name'];
            $order['district_name'] = $user_address['district_name'];
            $order['address'] = $user_address['address'];
            $order['province_id'] = $user_address['province_id'];
            $order['city_id'] = $user_address['city_id'];
            $order['district_id'] = $user_address['district_id'];
            $order['createtime'] = time();
            $order['order_id'] = $order_id;
            $order['user_id'] = $user_id;
            return $order;
        }
        return false;
    }

    public function addRessOrder1($jy_id, $user_id, $params)
    {
        $user_address = DetentionPrison::where(['id' => $jy_id])->find();
        if ($user_address) {
            $province_name = Area::where(['id' => $user_address['province_id']])->value('name');
            $city_name = Area::where(['id' => $user_address['city_id']])->value('name');
            $district_name = Area::where(['id' => $user_address['area_id']])->value('name');
            $order['mobile'] = $user_address['tel'];
            $order['consignee'] = $user_address['name'];
            $order['province_name'] = $province_name;
            $order['city_name'] = $city_name;
            $order['district_name'] = $district_name;
            $order['address'] = $user_address['address'];
            $order['province_id'] = $user_address['province_id'];
            $order['city_id'] = $user_address['city_id'];
            $order['district_id'] = $user_address['area_id'];
            $order['createtime'] = time();
            $order['user_id'] = $user_id;
            $order['consignee_j'] = $params['realname'];
            $order['mobile_j'] = $params['phone'];
            $order['address_j'] = $params['address'];
            return $order;
        }
        return false;
    }

}
